import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ThreeSum {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> ret = new ArrayList<>();
        if (nums[0] > 0 || nums[nums.length-1] < 0) {
            return ret;
        }
        for (int i = 0; i < nums.length-2 && nums[i] <= 0; i++) {
            if (i > 0 && nums[i] == nums[i-1]) {
                continue;
            }
            int target = -nums[i];
            int j = i+1, k = nums.length-1;
            while (j < k) {
                int sum = nums[j] + nums[k];
                if (sum == target) {
                    ret.add(Arrays.asList(nums[i], nums[j], nums[k]));
                    j++;
                    k--;
                } else if (sum > target) {
                    k--;
                } else {
                    j++;
                }
                while (j < k && j != i+1 && nums[j] == nums[j-1]) {
                    j++;
                }
                while (j < k && k < nums.length-1 && nums[k] == nums[k+1]) {
                    k--;
                }
            }
        }
        return ret;
    }

    public static void main(String[] args) {
        int[] nums = {-1,0,1,2,-1,-4,-2,-3,3,0,4};
        List<List<Integer>> ret = new ThreeSum().threeSum(nums);
        for (List<Integer> list : ret) {
            for (int i : list) {
                System.out.print(i + " ");
            }
            System.out.println();
        }
    }
}
